import { Body, HttpException, HttpStatus, Injectable, Post } from '@nestjs/common';
import { CreateFileDto, CreateFileFolders } from './dto/create-file.dto';
import { UpdateFileDto } from './dto/update-file.dto';
import * as fs from 'fs';
import * as path from 'path';
import * as process from 'node:process';
import { ConfigService } from '@nestjs/config';
import { FileFoldersController } from './file.controller';

const basePath: string = path.join(process.cwd(), 'public/images');

@Injectable()
export class FileService {
  constructor(
    private configService: ConfigService,
  ) {
  }

  getFilesRecursively(directory) {
    const result = {
      folders: [],
      files: [],
    };
    try {
      const items = fs.readdirSync(directory); // 获取目录下的所有文件和文件夹
      items.forEach((item) => {
        const fullPath = path.join(directory, item); // 构建完整路径
        const stats = fs.statSync(fullPath); // 获取文件状态
        if (stats.isDirectory()) {
          // 如果是目录，
          result.folders.push(item);
        } else if (stats.isFile()) {
          // 如果是文件，添加到结果
          result.files.push(`${this.configService.get<string>('FILE_IMAGES')}${item}`);
        }
      });
    } catch (err) {
      console.error(`Error reading directory ${directory}:`, err);
    }
    return result;
  }


  create(createFileDto: CreateFileDto) {
    return 'This action adds a new file';
  }


  async findAll() {
    return this.getFilesRecursively(basePath);
  }

  findOne(id: number) {
    return `This action returns a #${id} file`;
  }

  update(id: number, updateFileDto: UpdateFileDto) {
    return `This action updates a #${id} file`;
  }

  remove(id: number) {
    return `This action removes a #${id} file`;
  }
}


@Injectable()
export class FileFoldersService {
  create(createFileFolders: CreateFileFolders) {
    const targetPath:string = path.join(basePath, createFileFolders.name);
    try {
      // 判断目标路径是否存在并且是一个目录
      if (fs.existsSync(targetPath)) {
        if (fs.statSync(targetPath).isDirectory()) {
          throw new HttpException("此目录已存在",HttpStatus.INTERNAL_SERVER_ERROR)
          // 409 状态码
        } else {
          throw new HttpException("同名文件已存在",HttpStatus.INTERNAL_SERVER_ERROR)
        }
      }
      // 创建目录
      fs.mkdirSync(targetPath, { recursive: true });
      return '目录创建成功';
    } catch (err) {
      if (err instanceof HttpException) {
        throw err; // 抛出自定义异常
      }
      console.error(`Error creating directory: ${err.message}`);
      throw new HttpException('目录创建失败', HttpStatus.INTERNAL_SERVER_ERROR); // 500 状态码
    }
  }
}